<?php

namespace App\Service\Moment;

use App\Constants\ErrorCode;
use App\Event\PubMomentEvent;
use App\Model\BlackWords;
use App\Model\Moment;
use App\Model\UserProfile;
use App\Service\BaseService;
use Psr\EventDispatcher\EventDispatcherInterface;
/**
 * 动态发布
 */
class MomentPublishService extends BaseService
{
    public function handle()
    {
        $userId = $this->getUserId();
        $words = $this->request->input('words', '');
        $images = $this->request->input('images', '');
        $voice = $this->request->input('voice', '');
        $voiceDuration = $this->request->input('voice_duration', 0);
        $videoDuration = $this->request->input('video_duration', 0);
        $videoSize = $this->request->input('video_size', '');
        $video = $this->request->input('video', '');
        $videoPoster = $this->request->input('video_poster', '');
        if (!$words && !$images && !$voice && !$video) {
            return $this->setError(ErrorCode::PARAMETER_ERROR, '参数不完整，请重新传入参数！');
        }

        $check = BlackWords::checkLegal($words);
        if ($check['result'] != 1) {
            return $this->setError(ErrorCode::INPUT_SENSITIVE, '你的输入有违规文字，请重新输入～');
        }

        if ($images) {
            $images = array_unique(explode(',', $images));
            $images = count($images) > 9 ? array_slice($images, 0, 9) : $images;
        }
        $voiceInfo = $voiceDuration && $voice ? json_encode([
            'link' => $voice,
            'duration' => $voiceDuration > 60 ? 60 : intval($voiceDuration),
        ]) : '';

        $videoSize = $videoSize ? explode(',', $videoSize) : [];
        $videoInfo = !$video ? '' : json_encode([
            'link' => $video,
            'duration' => $videoDuration > 60 ? 60 : intval($videoDuration),
            'width' => $videoSize ? intval($videoSize[0]) : 0,
            'height' => $videoSize ? intval($videoSize[1]) : 0,
            'poster' => $videoPoster ?? '',
        ]);

        $userProfile = UserProfile::getProfile($userId);
        $ret = Moment::create([
            'user_id' => $userId,
            'user_gender' => $userProfile->gender,
            'words' => $words,
            'images' => $images,
            'voice' => $voiceInfo,
            'video' => $videoInfo,
            'status' => Moment::STATUS_VERIFING
        ]);

        //动态事件
	//make(EventDispatcherInterface::class)->dispatch(new PubMomentEvent($userId, $ret['id']));

	return [
            'result' => $ret ? 1 : 0,
            'tip' => '你的动态将进入审核, 审核后方可公开展示~',
        ];
    }
}
